package com.dap.oss.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import com.dap.oss.UploadService;
import com.dap.oss.config.OSSConfig;
import com.dap.utils.DateUtil;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SingleUploadService implements InitializingBean, UploadService {

    //OSS参数配置类
    @Autowired
    private OSSConfig ossConfig;
    private OSSClient client;

    @Override
    public void afterPropertiesSet() throws Exception {
        client = new OSSClient(this.ossConfig.getEndpoint(),
                               this.ossConfig.getAccessKeyId(),
                               this.ossConfig.getAccessKeySecret());
    }

    @Override
    public OSSConfig getOSSConfig() {
        return ossConfig;
    }


    /**
     * Object是OSS中最基本的数据单元，您可以把它简单地理解为文件，用下面代码可以实现一个Object的上传
     */
    @Override
    public PutObjectResult putObject(String bucketName, String key, InputStream inputStream, long contentLength) {
        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();
        // 必须设置ContentLength
        meta.setContentLength(contentLength);

        return putObject(bucketName, key, inputStream, meta);
    }
    @Override
    public PutObjectResult putObject(String bucketName, String key, InputStream inputStream, ObjectMetadata meta) {
        return client.putObject(bucketName, key, inputStream, meta);
    }

    @Override
    public DeleteObjectsResult removeObject(String bucketName, List<String> keys) {
        DeleteObjectsResult deleteObjectsResult =
                client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
        return deleteObjectsResult;
    }

    @Override
    public List<OSSObjectSummary> listObjects(String bucketName, String prefix) {
        // 获取指定bucket下的所有Object信息
        ObjectListing listing = client.listObjects(bucketName, prefix);
        return listing.getObjectSummaries();
    }

    @Override
    public CopyObjectResult copyObject(String sourceBucketName, String sourceKey,
            String destinationBucketName, String destinationKey) throws OSSException, ClientException {
        return client.copyObject(sourceBucketName, sourceKey, destinationBucketName, destinationKey);
    }

    @Override
    public String moveTempObject(String fullUrl) throws OSSException, ClientException {
        String sourceFileName = ossConfig.resolveFileNameFromFullUrl(fullUrl);
        if (null == sourceFileName) {
            return null;
        }
        if (!sourceFileName.startsWith(tempFilesPathPrefix)) {
            return null;
        }
        String destFileName = sourceFileName.substring(tempFilesPathPrefix.length());

        copyObject(ossConfig.getBucket(), sourceFileName, ossConfig.getBucket(), destFileName);
        removeObject(ossConfig.getBucket(), Lists.newArrayList(sourceFileName));
        return ossConfig.resolveFullUrl(destFileName);
    }



    /**
     * 删除开发测试环境老的文件
     * */
    private static void deleteDevOldFiles() {
        final long dayMillis = 24*3600*1000L;
        final long startMillis = DateUtil.parse("20181015", "yyyyMMdd").getTime();
        final long endMillis = System.currentTimeMillis() - 365*dayMillis;

        List<String> files = new ArrayList<>();
        for (long currentMillis = startMillis; currentMillis <= endMillis; currentMillis+=dayMillis) {
            Date date = new Date(currentMillis);
            final String baseDir = DateUtil.format(date, "yyyyMMdd");
            files.add(baseDir);
        }

        deleteDevSelectedFiles(files);
    }
    private static void deleteDevSelectedFiles(List<String> files) {
        final String devBucketName = "sunriseapp";

        OSSClient client = new OSSClient("http://oss-cn-shanghai.aliyuncs.com", "LTAIu2iimRmdNEDa", "2sDRy2hpXucfXGLUp8TauMGN1jYiFr");

        for (String baseDir : files) {
            ObjectListing listing = client.listObjects(devBucketName, baseDir);
            ArrayList<String> keys = new ArrayList<>();
            for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                keys.add(objectSummary.getKey());
            }
            if (!keys.isEmpty()) {
                DeleteObjectsRequest r = new DeleteObjectsRequest(devBucketName).withKeys(keys);
                r.setQuiet(true);
                client.deleteObjects(r);
            }

            client.deleteObject(new DeleteObjectsRequest(devBucketName).withKey(baseDir));
        }
    }
    public static void main(String[] args) {
        List<String> files = new ArrayList<>();
        files.add("");
        deleteDevSelectedFiles(files);
    }

}
